// ignore_for_file: use_build_context_synchronously

import 'package:client_flutter_door/http/box.dart';
import 'package:client_flutter_door/http/door.dart';
import 'package:client_flutter_door/bean/cabinet.dart';
import 'package:client_flutter_door/model/door_model.dart';
import 'package:client_flutter_door/vars.dart';
import 'package:client_flutter_door/widgets/btn.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:client_flutter_door/utils/info.dart';

class Func extends StatefulWidget {
  const Func({super.key});

  @override
  State<Func> createState() => _FuncState();
}

class _FuncState extends State<Func> {
  final TextEditingController _controller = TextEditingController(text: '');

  bool isSetPermanet = false; //默认临时开柜
  late int len;

  @override
  void initState() {
    super.initState();
    len = Vars.navigatorKey.currentContext!
        .read<DoorModel>()
        .boxs
        .length
        .toString()
        .length;
    _controller.addListener(() async {
      //100个柜子：1号就是001,几十个柜子1号就是01
      // final permanentLength = Door.openDoors.length.toString().length;

      if (_controller.text.length != 4 && _controller.text.length != len + 4)
        return;
      var boxs = Provider.of<DoorModel>(context, listen: false).boxs;
      Cabinet? czhNotEmpty; //匹配车组的柜子
      Cabinet? czh2; //匹配的CR400AF车组的柜子
      //临时就是4位
      if (!isSetPermanet && _controller.text.length == 4) {
        // Cabinet? czhEmpty; //第一个空柜子

        for (var i = 0; i < boxs.length; i++) {
          // if (czhEmpty == null && boxs[i].czh == '') {
          //   czhEmpty = boxs[i];
          // }
          if (czhNotEmpty == null && boxs[i].czh == _controller.text) {
            czhNotEmpty = boxs[i];
            continue;
          }
          //一定是第二次匹配了
          if (czhNotEmpty != null && boxs[i].czh == _controller.text) {
            czh2 = boxs[i];
          }
        }

        //匹配车组的柜子开门
        if (czhNotEmpty != null) {
          if (czh2 == null) {
            await Door.open(czhNotEmpty.BlId);
            Info.snackbarWithoutContext('${czhNotEmpty.id}号柜门已打开');
          } else {
            AlertDialog alert = AlertDialog(
              title: const Text('车型确认'),
              content: Text('请选择要打开柜门的车组${_controller.text}的车型！！！'),
              actions: <Widget>[
                // 取消按钮
                TextButton(
                  onPressed: () async {
                    Navigator.of(context).pop(); // 关闭对话框
                    await Door.open((czhNotEmpty!.is400AF)
                        ? (czh2!.BlId)
                        : (czhNotEmpty.BlId));
                    Info.snackbarWithoutContext('${czhNotEmpty.id}号柜门已打开');
                  },
                  child: const Text('普通没S'),
                ),
                // 确认按钮
                TextButton(
                  onPressed: () async {
                    Navigator.of(context).pop(); // 关闭对话框
                    await Door.open((czhNotEmpty!.is400AF)
                        ? (czhNotEmpty.BlId)
                        : (czh2!.BlId));
                    Info.snackbarWithoutContext('${czh2!.id}号柜门已打开');
                  },
                  child: const Text('智能S'),
                ),
              ],
            );
            // 显示对话框
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return alert;
              },
            );
          }
        } else {
          Info.snackbar('不存在车组号：${_controller.text}', context);
        }
        //   //第一个空柜子
        //   else if (czhEmpty != null) {
        //     final indexStr = czhEmpty.cabinetindex;

        //     //不存在：
        //     //修改状态

        //     //开门
        //     await Cabinet.setBox(int.parse(indexStr), _controller.text);
        //       // ignore: use_build_context_synchronously
        //       await Provider.of<DoorModel>(context).getBoxs();
        //       await Door.open(int.parse(indexStr));

        //   }
        _controller.text = '';
      } else if (isSetPermanet && _controller.text.length == len + 4) {
        final id = int.parse(_controller.text.substring(0, len));
        final czh = _controller.text.substring(len);
        _controller.text = '';

        //查找是否已存在
        //1按车组号
        final existBoxCzh = boxs.firstWhereOrNull((box) {
          if (box.czh.contains(czh)) {
            return true;
          } else {
            return false;
          }
        });
        //2按柜门编号
        final existBoxId = boxs.firstWhereOrNull((box) {
          if (box.BlId == id) {
            return true;
          } else {
            return false;
          }
        });

        // final existBox = boxs.firstWhereOrNull((box) {
        //   if (box.BlId == id&&box.czh==czh) {
        //     return true;
        //   } else {
        //     return false;
        //   }
        // });

        //不存在
        if (existBoxId == null) {
          //柜门编号输入错误
          Info.snackbar('$id号柜不存在', context);
          return;
        }
        bool isBinding = false;
        //移除+绑定
        AlertDialog alertBingd = AlertDialog(
          title: const Text('操作确认'),
          content: Text('请选择要对${_controller.text}车组的操作！！！'),
          actions: <Widget>[
            // 取消按钮
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop(); // 关闭对话框
                isBinding = false;
              },
              child: const Text('移除绑定'),
            ),
            // 确认按钮
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop(); // 关闭对话框
                isBinding = true;
              },
              child: const Text('添加绑定'),
            ),
          ],
        );

        await showDialog(
          context: context,
          builder: (BuildContext context) {
            return alertBingd;
          },
        );

        //添加绑定
        if (isBinding) {
          bool is400AF = false;
          AlertDialog alert = AlertDialog(
            title: const Text('车型确认'),
            content: Text('请选择要添加绑定车组${_controller.text}的车型！！！'),
            actions: <Widget>[
              // 取消按钮
              TextButton(
                onPressed: () async {
                  Navigator.of(context).pop(); // 关闭对话框
                  is400AF = false;
                },
                child: const Text('普通没S'),
              ),
              // 确认按钮
              TextButton(
                onPressed: () async {
                  Navigator.of(context).pop(); // 关闭对话框
                  is400AF = true;
                },
                child: const Text('智能S'),
              ),
            ],
          );

          if (existBoxCzh == null) {
            // 显示对话框
            await showDialog(
              context: context,
              builder: (BuildContext context) {
                return alert;
              },
            );
            //绑定车组
            await Box.setBox(id.toString(), czh, true, is400AF);
            Info.snackbar('绑定成功：车组号$czh对应的${existBoxId.id}号柜已设置成功', context);
          } else {
            final existBoxLast = boxs.lastWhereOrNull((box) {
              if (box.czh == czh) {
                return true;
              } else {
                return false;
              }
            });
            final List<Cabinet> count = boxs.where((box) {
              if (box.czh == czh) {
                return true;
              } else {
                return false;
              }
            }).toList();
            if (count.length > 1) {
              Info.snackbar(
                  '绑定失败：车组号$czh分别在${count[0].id}号柜${count[1].id}号柜', context);
              return;
            }
            //只有一个
            if (existBoxLast!.id == existBoxCzh.id) {
              if (existBoxCzh.id != id) {
                //绑定车组:上一个上和谐号，这个就是复兴号，上一个是复兴号，这个就是和谐号
              await Box.setBox(id.toString(), czh, true, !existBoxCzh.is400AF);
              Info.snackbar('绑定成功：车组号$czh对应的${existBoxId.id}号柜已设置成功', context);
              }else{

              }
              
            }
            //不会执行到
            else {
              Info.snackbar(
                  '绑定失败：车组号$czh分别在${existBoxCzh.id}号柜${existBoxLast.id}号柜',
                  context);
            }
          }
        } else {
          //移除绑定
          if (existBoxCzh == null) {
            Info.snackbar('移除绑定失败：车组号$czh不存在', context);
            return;
          }

          final existInfo = boxs.firstWhereOrNull((box) {
            if (box.BlId == id && box.czh == czh) {
              return true;
            } else {
              return false;
            }
          });

          if (existInfo != null) {
            await Box.setBox(id.toString(), '', false, false);
            Info.snackbar('移除绑定成功：车组号$czh对应的${existBoxId.id}号柜已清除', context);
          } else {
            Info.snackbar('移除绑定失败：车组号$czh不在对应的$id号柜', context);
          }
        }

        await Provider.of<DoorModel>(context, listen: false).getBoxs();
        // await Door.open(int.parse(num));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Column(
          children: [
            Container(
              margin: const EdgeInsets.all(20),
              // child: TextField(
              //   controller: controller,
              //   decoration: InputDecoration(
              //     helperText: helperText,
              //     border: OutlineInputBorder(
              //       borderRadius: BorderRadius.circular(10),
              //     ),
              //   ),
              // ),
              child: TextField(
                controller: _controller,
                decoration: InputDecoration(
                  hintText:
                      '${isSetPermanet ? '存取设置' : '临时开门'}:${isSetPermanet ? '输入$len位柜门编号+4位车组号：譬如1号就是${'0' * (len - 1)}1、12就是${'0' * (len - 2)}12' : '输入4位车组号'}',
                  helperText: Provider.of<DoorModel>(context).getHelperText(),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              ),
            ),
            SizedBox(
              width: double.infinity,
              height: 300,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      ElevatedButton(
                        onPressed: () async {
                          var boxs = Provider.of<DoorModel>(context).boxs;
                          for (var i = 0; i < boxs.length; i++) {
                            if (boxs[i].czh == '') {
                              await Door.open(boxs[i].BlId);
                            }
                          }
                        },
                        child: const Text('一键开空柜'),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          var boxs = Provider.of<DoorModel>(context).boxs;
                          for (var i = 0; i < boxs.length; i++) {
                            if (boxs[i].czh.length == 4) {
                              await Door.open(boxs[i].BlId);
                            }
                          }
                        },
                        child: const Text('一键开占用柜'),
                      ),
                      ElevatedButton(
                        onPressed: () async {
                          var boxs = Provider.of<DoorModel>(context).boxs;
                          for (var i = 0; i < boxs.length; i++) {
                            await Door.open(boxs[i].BlId);
                          }
                        },
                        child: const Text('一键开所有柜子'),
                      ),
                      Row(
                        children: [
                          Switch(
                            // This bool value toggles the switch.
                            value: isSetPermanet,
                            onChanged: (bool value) {
                              // This is called when the user toggles the switch.
                              setState(() {
                                isSetPermanet = value;
                              });
                            },
                          ),
                          Text(isSetPermanet ? '存取设置' : '临时开门'),
                        ],
                      )
                    ],
                  ),
                  Row(children: [
                    Column(
                      children: [
                        Btn(
                          title: '1',
                          onTap: () {
                            _controller.text = '${_controller.text}1';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '4',
                          onTap: () {
                            _controller.text = '${_controller.text}4';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '7',
                          onTap: () {
                            _controller.text = '${_controller.text}7';
                          },
                          onTagTap: () {},
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        Btn(
                          title: '2',
                          onTap: () {
                            _controller.text = '${_controller.text}2';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '5',
                          onTap: () {
                            _controller.text = '${_controller.text}5';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '8',
                          onTap: () {
                            _controller.text = '${_controller.text}8';
                          },
                          onTagTap: () {},
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        Btn(
                          title: '3',
                          onTap: () {
                            _controller.text = '${_controller.text}3';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '6',
                          onTap: () {
                            _controller.text = '${_controller.text}6';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '9',
                          onTap: () {
                            _controller.text = '${_controller.text}9';
                          },
                          onTagTap: () {},
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        Btn(
                          title: '清',
                          onTap: () {
                            _controller.text = '';
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '删',
                          onTap: () {
                            if (_controller.text.isEmpty) {
                              return;
                            }
                            _controller.text = _controller.text
                                .substring(0, _controller.text.length - 1);
                          },
                          onTagTap: () {},
                        ),
                        Btn(
                          title: '0',
                          onTap: () {
                            _controller.text = '${_controller.text}0';
                          },
                          onTagTap: () {},
                        ),
                      ],
                    ),
                  ]),
                ],
              ),
            ),
          ],
        ),
        Container(
          // color: Theme.of(context).colorScheme.secondary,
          padding: const EdgeInsets.all(20),
          child: DefaultTextStyle(
              style: Theme.of(context).textTheme.titleMedium!,
              child: Center(
                child: Text(
                    '提示：${isSetPermanet ? '输入$len位柜门编号+4位车组号：譬如1号就是${'0' * (len - 1)}1、12就是${'0' * (len - 2)}12' : '输入4位车组号'}'),
              )),
        )
      ],
    );
  }
}
